<template>
  <div class="preview" ref="preview"></div>
</template>

<script>
import * as PIXI from "pixi.js";
export default {
  components: {},
  data() {
    return {
      app: null,
      map: "",
      width: 0,
      height: 0,
    };
  },
  created() {
    this.$bus.$on("draw", ({ width, height, data }) => {
      this.map = data;
      if (this.width != width || this.height != height) {
        this.width = width;
        this.height = height;
        this.destroy();
      }
      this.$nextTick().then(() => {
        if (this.app == null) this.createPreview();
        this.app && this.drawGraphics();
      });
    });
  },
  mounted() {},
  methods: {
    createPreview() {
      this.app = new PIXI.Application({
        width: this.width,
        height: this.height,
        backgroundColor: 0xffffff,
        resolution: this.$refs.preview.offsetWidth / this.width,
        antialias: true,
        preserveDrawingBuffer: true,
      });
      this.graphics = new PIXI.Graphics();

      this.app.stage.addChild(this.graphics);
      this.$refs.preview.appendChild(this.app.view);
    },
    drawGraphics() {
      this.graphics.clear();
      for (let i = 0, len = this.map.length; i < len; ++i) {
        const { x, y, color, alpha } = this.map[i];
        let _color = color == "" ? "0xFFFFFF" : color;
        this.graphics.beginFill(_color, alpha);
        this.graphics.drawRect(x, y, 1, 1);
        this.graphics.endFill();
      }
    },
    destroy() {
      this.app && this.app.destroy(true, true);
      this.app = null;
    },
  },
};
</script>

<style scoped lang="scss">
</style>
